﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;

namespace SimpleSocket
{
    /// <summary>
    /// Derive this abstract class to create your own client instance object
    /// <example> This sample shows how to create your Client class.
    /// <code><![CDATA[
    /// public class Player : SimpleSocket.Client
    /// {
    ///     public Player()
    ///     {
    /// 
    ///     }
    ///     public override void ReceiveLine(string s)
    ///     {
    ///         WriteLine(s);
    ///     }
    ///     public override void Disconnected()
    ///     {
    ///         
    ///     }
    /// }
    /// ]]></code>
    /// </example>
    /// </summary>
    public abstract class Client
    {

        private Socket _socket;
        internal Socket Socket
        {
            get { return _socket; }
            set { _socket = value; }
        }

        StringBuilder buffer = new StringBuilder();
 
        internal void ReceiveData(string s)
        {
            if(string.Equals(s,"\0\0"))
            {
                if (buffer.Length > 0)
                {
                    ReceiveLine(buffer.ToString());
                    buffer = new StringBuilder();
                }
            }
            else
            {
                buffer.Append(s.Remove(s.Length - 1));
            }
            
        }

        /// <summary>
        /// Override this method in order to receive data
        /// </summary>
        /// <param name="s"></param>
        public abstract void ReceiveLine(string s);

        /// <summary>
        /// Disconnect the client
        /// </summary>
        public void Disconnect()
        {
            if (Socket != null && Socket.Connected)
            {
                Socket.DisconnectAsync(new SocketAsyncEventArgs());
            }
        }

        /// <summary>
        /// Write output lines to this method
        /// </summary>
        /// <param name="s"></param>
        public virtual void WriteLine(string s)
        {
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(string.Format("{0}\r\n\0",s));
            if (this.Socket.Connected)
            {
                this.Socket.Send(byData);
            }
        }

        /// <summary>
        /// Override this method in order to handle disconnection
        /// </summary>
        /// <param name="s"></param>
        public abstract void Disconnected();
    }
}
